<template>
  <div class="page-container">
    <!-- Main Content -->
    <div class="main-content">
      <el-row :gutter="20">
        <!-- Order Creation Form -->
        <el-col :span="16">
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center; justify-content: space-between;">
                <span style="font-size: 16px; font-weight: 600;">Create Payment Order</span>
                <el-tag type="info">Please fill in complete information</el-tag>
              </div>
            </template>

            <el-form
              ref="orderFormRef"
              :model="orderForm"
              :rules="orderRules"
              label-width="140px"
              style="max-width: 600px;"
            >
              <!-- Payment Channel Selection -->
              <el-form-item label="Payment Channel" prop="paymentChannel">
                <el-select
                  v-model="orderForm.paymentChannel"
                  placeholder="Please select payment channel"
                  style="width: 100%;"
                  @change="handleChannelChange"
                >
                  <el-option
                    v-for="channel in availableChannels"
                    :key="channel.value"
                    :label="channel.label"
                    :value="channel.value"
                  />
                </el-select>
              </el-form-item>

              <!-- Payment Method Selection -->
              <el-form-item label="Payment Method" prop="paymentMethod">
                <el-select
                  v-model="orderForm.paymentMethod"
                  placeholder="Please select payment method"
                  style="width: 100%;"
                >
                  <el-option label="Bank Transfer" value="BankTransfer" />
                  <el-option label="QR Code Payment" value="qrPay" />
                </el-select>
              </el-form-item>

              <!-- User Information -->
              <el-form-item label="User UID" prop="uid">
                <el-input
                  v-model="orderForm.uid"
                  placeholder="Please enter user UID"
                  clearable
                />
              </el-form-item>

              <!-- Payment Amount -->
              <el-form-item label="Payment Amount" prop="amount">
                <el-input-number
                  v-model="orderForm.amount"
                  :min="0.01"
                  :max="500000"
                  :precision="2"
                  placeholder="Please enter payment amount"
                  style="width: 100%;"
                />
                <small style="color: #999; display: block; margin-top: 4px;">
                  Single payment amount should not exceed 500,000 THB
                </small>
              </el-form-item>

              <!-- Receiver Information -->
              <el-divider content-position="left">Receiver Information</el-divider>
              
              <el-form-item label="Receiver Name" prop="receiverName">
                <el-input
                  v-model="orderForm.receiverName"
                  placeholder="Please enter receiver's real name"
                  clearable
                />
              </el-form-item>

              <el-form-item label="Receiver Bank Card Number" prop="receiverBankCard">
                <el-input
                  v-model="orderForm.receiverBankCard"
                  placeholder="Please enter receiver's bank card number (10-20 digits)"
                  maxlength="20"
                  clearable
                />
              </el-form-item>

              <el-form-item
                label="Receiver Bank"
                prop="bankCode"
              >
                <el-select
                  v-model="orderForm.bankCode"
                  placeholder="Please select receiver bank"
                  style="width: 100%;"
                  clearable
                  filterable
                  :allow-create="orderForm.paymentChannel === 'HUIFENG'"
                >
                  <el-option
                    v-for="bank in bankOptions"
                    :key="bank.value"
                    :label="bank.label"
                    :value="bank.value"
                  />
                </el-select>
                <small style="color: #999; display: block; margin-top: 4px;">
                  {{ orderForm.paymentChannel === 'LSPPAY'
                    ? 'LSPPAY payout requires bank code for proper transfer routing'
                    : 'Selecting the correct bank can improve payment success rate' }}
                </small>
              </el-form-item>

              <!-- Other Information -->
              <el-divider content-position="left">Other Information</el-divider>

              <el-form-item label="Customer Service" prop="createdByName">
                <el-input
                  v-model="orderForm.createdByName"
                  placeholder="Please enter customer service name"
                  clearable
                />
              </el-form-item>


              <el-form-item label="Payment Remark" prop="remark">
                <el-input
                  v-model="orderForm.remark"
                  type="textarea"
                  :rows="3"
                  placeholder="Payment remark (optional, max 200 characters)"
                  maxlength="200"
                  show-word-limit
                />
              </el-form-item>

              <!-- Submit Button -->
              <el-form-item style="margin-top: 30px;">
                <el-button
                  type="primary"
                  size="large"
                  @click="handleSubmit"
                  :loading="isSubmitting"
                  :disabled="!isFormValid"
                >
                  <el-icon class="el-icon--left"><Plus /></el-icon>
                  Create Payment Order
                </el-button>
                <el-button size="large" @click="handleReset">
                  Reset Form
                </el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>

        <!-- Help Information -->
        <el-col :span="8">
          <el-card shadow="hover" style="margin-bottom: 20px;">
            <template #header>
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><InfoFilled /></el-icon>
                <span>Instructions</span>
              </div>
            </template>

            <div class="help-content">
              <h4>Payment Channel</h4>
              <ul>
                <li>TopPay: Thailand's mainstream payment platform</li>
                <li>668Pay: Supports multiple payment methods</li>
                <li>LSPPAY: PromptPay QR code payment platform</li>
              </ul>

              <h4>Payment Method</h4>
              <ul>
                <li>Bank Transfer: Direct bank card transfer</li>
                <li>QR Code Payment: Generate QR code payment</li>
              </ul>

              <h4>Important Reminders</h4>
              <ul>
                <li>Please ensure receiver information is accurate</li>
                <li>Bank card number must be 10-20 digits</li>
                <li>Payment amount should not exceed 500,000 THB</li>
                <li>Requires administrator confirmation after creation</li>
              </ul>
            </div>
          </el-card>

          <!-- Payment Channel Status -->
          <el-card shadow="hover">
            <template #header>
              <div style="display: flex; align-items: center;">
                <el-icon style="margin-right: 8px;"><Setting /></el-icon>
                <span>Channel Status</span>
              </div>
            </template>

            <div v-if="channelStatus.length > 0">
              <div
                v-for="channel in channelStatus"
                :key="channel.channel"
                style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 12px;"
              >
                <span>{{ channel.displayName }}</span>
                <el-tag :type="channel.isConfigured ? 'success' : 'danger'">
                  {{ channel.isConfigured ? 'Configured' : 'Not Configured' }}
                </el-tag>
              </div>
            </div>
            <div v-else>
              <el-text type="info">Loading channel status...</el-text>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, InfoFilled, Setting } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import { trpc } from '../utils/trpc'

// Reactive data
const orderFormRef = ref<FormInstance>()
const isSubmitting = ref(false)
const availableChannels = ref<Array<{ value: string; label: string; configured: boolean }>>([])
const channelStatus = ref<Array<{ channel: string; displayName: string; isConfigured: boolean }>>([])

// Form data
const orderForm = reactive({
  paymentChannel: '',
  paymentMethod: 'BankTransfer',
  uid: '',
  amount: null as number | null,
  receiverName: '',
  receiverBankCard: '',
  bankCode: '',
  createdByName: '',
  remark: ''
})

// 银行编码选项数据
const topPayBankOptions = [
  { label: 'Kasikorn Bank Plc. (KBANK)', value: '001' },
  { label: 'Bangkok Bank Plc. (BBL)', value: '003' },
  { label: 'Krung Thai Bank (KTB)', value: '004' },
  { label: 'ABN Amro Bank N.V. (ABN)', value: '005' },
  { label: 'TMBThanachart (TTB)', value: '007' },
  { label: 'Siam Commercial Bank (SCB)', value: '010' },
  { label: 'UOB Bank Plc. (UOB)', value: '016' },
  { label: 'Bank of Ayudhya / Krungsri (BAY)', value: '017' },
  { label: 'CIMB Thai Bank Public Company Limited (CIMB)', value: '018' },
  { label: 'Land and Houses Bank Public Company Limited (LHBANK)', value: '020' },
  { label: 'Government Savings Bank (GSB)', value: '022' },
  { label: 'Kiatnakin Phatra Bank Public Company Limited (KKP)', value: '023' },
  { label: 'Citibank N.A. (CITI)', value: '024' },
  { label: 'Government Housing Bank (GHB)', value: '025' },
  { label: 'Bank for Agriculture and Agricultural Cooperatives (BAAC)', value: '026' },
  { label: 'Mizuho Corporate Bank Limited (MHCB)', value: '027' },
  { label: 'Islamic Bank of Thailand (IBANK)', value: '028' },
  { label: 'TISCO Bank Plc. (TISCO)', value: '029' }
]

const pay668BankOptions = [
  { label: 'BANK FOR AGRICULTURE AND AGRICULTURAL CO-OPERATIVES (BAAC)', value: 'BAAC' },
  { label: 'BANK OF AYUDHAYA PUBLIC COMPANY LTD. (BAY)', value: 'BAY' },
  { label: 'BANGKOK BANK PUBLIC COMPANY LTD. (BBL)', value: 'BBL' },
  { label: 'BNP PARIBAS BANGKOK BRANCH (BNPP)', value: 'BNPP' },
  { label: 'BANK OF AMERICA NT&SA (BOA)', value: 'BOA' },
  { label: 'Bank of China (Thai) PCL (BOC)', value: 'BOC' },
  { label: 'BANK OF THAILAND (BOT)', value: 'BOT' },
  { label: 'JPMorgan Chase Bank, Bangkok Branch (CHAS)', value: 'CHAS' },
  { label: 'CIMB THAI BANK PUBLIC COMPANY LTD (CIMB)', value: 'CIMB' },
  { label: 'CITI BANK N.A. (CITI)', value: 'CITI' },
  { label: 'Deutsche Bank AG (DB)', value: 'DB' },
  { label: 'EXPORT–IMPORT BANK OF THAILAND (EXIM)', value: 'EXIM' },
  { label: 'GOVERNMENT HOUSING BANK (GHB)', value: 'GHB' },
  { label: 'THE GOVERNMENT SAVING BANK (GSB)', value: 'GSB' },
  { label: 'THE HONGKONG & SHANGHAI CORPORATION LTD (HSBC)', value: 'HSBC' },
  { label: 'Industrial and Commercial Bank of China (Thai) Public Company Limited (IACBC)', value: 'IACBC' },
  { label: 'INDUSTRIAL AND COMMERCIAL BANK OF CHINA (THAI) PCL (ICBC)', value: 'ICBC' },
  { label: 'INDIAN OVERSEAS BANK (IOB)', value: 'IOB' },
  { label: 'KASIKORNBANK PCL (KBANK)', value: 'KBANK' },
  { label: 'KIATNAKIN BANK PCL (KKP)', value: 'KKP' },
  { label: 'KRUNG THAI BANK PUBLIC COMPANY LTD. (KTB)', value: 'KTB' },
  { label: 'Land and Houses Bank (LHBA)', value: 'LHBA' },
  { label: 'MEGA INTERNATIONAL COMMERCIAL BANK (MEGA)', value: 'MEGA' },
  { label: 'MIZUHO CORPORATE BANK (MHCB)', value: 'MHCB' },
  { label: 'THE SIAM COMMERCIAL BANK PUBLIC COMPANY (SCB)', value: 'SCB' },
  { label: 'STANDARD CHARTERED BANK THAI PCL (SCBT)', value: 'SCBT' },
  { label: 'THE SUMITOMO MITSU BANKING CORPORATION (SMBC)', value: 'SMBC' },
  { label: 'Sumitomo Mitsui Trust Bank (Thai) PCL (SMTB)', value: 'SMTB' },
  { label: 'Thanachart Bank Public Company Limited (TBNK)', value: 'TBNK' },
  { label: 'THE THAI CREDIT RETAIL BANK (TCRB)', value: 'TCRB' },
  { label: 'ISLAMIC BANK OF THAILAND (TIBT)', value: 'TIBT' },
  { label: 'TISCO Bank PCL (TISCO)', value: 'TISCO' },
  { label: 'TMB BANK PUBLIC COMPANY LTD. (TMB)', value: 'TMB' },
  { label: 'TMBThanachart Bank Public Company Limited (TTB)', value: 'TTB' },
  { label: 'UNITED OVERSEAS BANK (THAI) PUBLIC COMPANY LTD. (UOB)', value: 'UOB' },
  { label: 'SME (SME)', value: 'SME' },
  { label: 'IBANK (IBANK)', value: 'IBANK' },
  { label: 'Krungsri (KRU)', value: 'KRU' }
]

const huifengBankOptions = [
  ...topPayBankOptions,
  ...pay668BankOptions
]


// LSPPAY 代付专用银行编码选项（基于 lspPayService.ts 中的 getBankNameByCode 映射）
const lspPayPayoutBankOptions = [
  { label: 'BANGKOK BANK PUBLIC COMPANY LIMITED', value: '002' },
  { label: 'KASIKORN BANK PUBLIC COMPANY LIMITED', value: '004' },
  { label: 'KRUIG THAI BANK PUBLIC COMPANY LIMITED', value: '006' },
  { label: 'TMBTHANACHART BANK', value: '011' },
  { label: 'SIAM COMMERCIAL BANK PUBLIC COMPANY LIMITED', value: '014' },
  { label: 'GTHBANK, N.A. (GBT), BANGKOK BRANCH', value: '017' },
  { label: 'SUMITOMO MITSUI BANKING CORPORATION', value: '018' },
  { label: 'STANDARD CHARTERED BANK (THAI) PUBLIC COMPANY LIMITED', value: '020' },
  { label: 'CIMB THAI BANK PUBLIC COMPANY LIMITED', value: '022' },
  { label: 'UNITED OVERSEAS BANK (THAI) PUBLIC COMPANY LIMITED', value: '024' },
  { label: 'BANK OF AYUDHYA PUBLIC COMPANY LIMITED', value: '025' },
  { label: 'GOVERNMENT SAVINGS BANK', value: '030' },
  { label: 'THE HONGKONG AND SHANGHAI BANKING CORPORATION LIMITED', value: '031' },
  { label: 'GOVERNMENT HOUSING BANK', value: '033' },
  { label: 'BANK FOR AGRICULTURE AND AGRICULTURAL COOPERATIVES', value: '034' },
  { label: 'MIZUHO CORPORATE BANK LIMITED', value: '039' },
  { label: 'ISLAMIC BANK OF THAILAND', value: '066' },
  { label: 'TISCO BANK PUBLIC COMPANY LIMITED', value: '067' },
  { label: 'KIATNAKIN BANK PUBLIC COMPANY LIMITED', value: '069' },
  { label: 'INDUSTRIAL AND COMMERCIAL BANK OF CHINA (THAI) PUBLIC COMPANY LIMITED', value: '070' },
  { label: 'THAI CREDIT RETAIL BANK PUBLIC COMPANY LIMITED', value: '071' },
  { label: 'LAND AND HOUSES BANK PUBLIC COMPANY LIMITED', value: '073' }
]

// Computed properties
const bankOptions = computed(() => {
  if (orderForm.paymentChannel === 'TOPPAY') {
    return topPayBankOptions
  } else if (orderForm.paymentChannel === 'PAY668') {
    return pay668BankOptions
  } else if (orderForm.paymentChannel === 'LSPPAY') {
    return lspPayPayoutBankOptions  // 使用代付专用的LSPPAY银行编码列表
  } else if (orderForm.paymentChannel === 'HUIFENG') {
    return huifengBankOptions
  }
  return [] // 未选择渠道时返回空数组
})

// Form validation rules
const orderRules = computed<FormRules>(() => ({
  paymentChannel: [
    { required: true, message: 'Please select payment channel', trigger: 'change' }
  ],
  paymentMethod: [
    { required: true, message: 'Please select payment method', trigger: 'change' }
  ],
  uid: [
    { required: true, message: 'Please enter user UID', trigger: 'blur' },
    { min: 1, max: 50, message: 'User UID length should be 1-50 characters', trigger: 'blur' }
  ],
  amount: [
    { required: true, message: 'Please enter payment amount', trigger: 'blur' },
    { type: 'number', min: 0.01, max: 500000, message: 'Payment amount must be between 0.01-500000', trigger: 'blur' }
  ],
  receiverName: [
    { required: true, message: 'Please enter receiver name', trigger: 'blur' },
    { min: 2, max: 50, message: 'Receiver name length should be 2-50 characters', trigger: 'blur' }
  ],
  receiverBankCard: [
    { required: true, message: 'Please enter receiver bank card number', trigger: 'blur' },
    { pattern: /^\d{10,20}$/, message: 'Bank card number must be 10-20 digits', trigger: 'blur' }
  ],
  bankCode: [
    { required: true, message: 'Please select receiver bank', trigger: 'change' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (!value) {
          callback(new Error('Please select receiver bank'))
          return
        }

        const channel = orderForm.paymentChannel
        if (channel === 'TOPPAY') {
          if (!/^\d{3}$/.test(value)) {
            callback(new Error('TopPay bank code must be 3 digits'))
            return
          }
        } else if (channel === 'PAY668') {
          if (!/^[A-Z]{2,10}$/.test(value)) {
            callback(new Error('Pay668 bank code must be bank abbreviation (e.g., KBANK, BBL)'))
            return
          }
        } else if (channel === 'HUIFENG') {
          if (!/^[A-Za-z0-9]{2,20}$/.test(value)) {
            callback(new Error('Huifeng bank code must be 2-20 letters or digits'))
            return
          }
        } else if (channel === 'LSPPAY') {
          if (!/^\d{3}$/.test(value)) {
            callback(new Error('LSPPAY bank code must be 3 digits'))
            return
          }
        }

        callback()
      },
      trigger: 'change'
    }
  ],
  createdByName: [
    { required: true, message: 'Please enter customer service name', trigger: 'blur' },
    { min: 2, max: 50, message: 'Customer service name length should be 2-50 characters', trigger: 'blur' }
  ],
  remark: [
    { max: 200, message: 'Remark cannot exceed 200 characters', trigger: 'blur' }
  ]
}))

// Computed properties
const isFormValid = computed(() => {
  return !!(
    orderForm.paymentChannel &&
    orderForm.paymentMethod &&
    orderForm.uid &&
    orderForm.amount &&
    orderForm.receiverName &&
    orderForm.receiverBankCard &&
    orderForm.createdByName
  )
})

// Methods
const handleChannelChange = () => {
  // Reset bank code when channel changes as different channels may have different bank codes
  orderForm.bankCode = ''
  
  // Clear form validation errors for bank code field
  orderFormRef.value?.clearValidate(['bankCode'])
}

const handleSubmit = async () => {
  if (!orderFormRef.value) return

  const valid = await orderFormRef.value.validate().catch(() => false)
  if (!valid) {
    ElMessage.error('Please check if the form is filled correctly')
    return
  }

  // Confirm submission
  const confirmed = await ElMessageBox.confirm(
    'Confirm to create payment order? The order requires administrator confirmation after creation before payment execution.',
    'Confirm Creation',
    {
      confirmButtonText: 'Confirm Creation',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  ).catch(() => false)

  if (!confirmed) return

  isSubmitting.value = true

  try {
    const rawBankCode = orderForm.bankCode?.trim() ?? ''
    const normalizedBankCode = (() => {
      // 移除 LSPPAY 的特殊处理,保留原始银行编码
      if (orderForm.paymentChannel === 'PAY668' || orderForm.paymentChannel === 'HUIFENG') {
        return rawBankCode.toUpperCase()
      }
      // LSPPAY 和 TOPPAY 都返回原始值
      return rawBankCode
    })()

    orderForm.bankCode = normalizedBankCode

    const result = await trpc.payout.create.mutate({
      paymentChannel: orderForm.paymentChannel as 'TOPPAY' | 'PAY668' | 'LSPPAY' | 'HUIFENG',
      paymentMethod: orderForm.paymentMethod as 'BankTransfer' | 'qrPay',
      uid: orderForm.uid,
      amount: orderForm.amount!,
      receiverName: orderForm.receiverName,
      receiverBankCard: orderForm.receiverBankCard,
      bankCode: normalizedBankCode || undefined, // 移除特殊判断,统一处理
      createdByName: orderForm.createdByName,
      remark: orderForm.remark || undefined,
    })

    if (result.success) {
      ElMessage.success('Payment order created successfully!')
      handleReset()
      // Can redirect to order detail page or list page
      // $router.push('/payout/query')
    } else {
      ElMessage.error(result.message || 'Failed to create payment order')
    }
  } catch (error: any) {
    console.error('Create payout order error:', error)
    ElMessage.error(error.message || 'Failed to create payment order')
  } finally {
    isSubmitting.value = false
  }
}

const handleReset = () => {
  orderFormRef.value?.resetFields()
  Object.assign(orderForm, {
    paymentChannel: '',
    paymentMethod: 'BankTransfer',
    uid: '',
    amount: null,
    receiverName: '',
    receiverBankCard: '',
    bankCode: '',
    createdByName: '',
    remark: ''
  })
}

const loadAvailableChannels = async () => {
  try {
    const result = await trpc.payout.getAvailableChannels.query()
    if (result.success) {
      availableChannels.value = result.data.channels
    }
  } catch (error) {
    console.error('Load available channels error:', error)
  }
}

const loadChannelStatus = async () => {
  try {
    const result = await trpc.payout.getAvailableChannels.query()
    if (result.success) {
      // Convert channel information to status display format
      channelStatus.value = result.data.channels.map((channel: any) => ({
        channel: channel.value,
        displayName: channel.label,
        isConfigured: channel.configured
      }))
    }
  } catch (error) {
    console.error('Load channel status error:', error)
  }
}

// Lifecycle
onMounted(async () => {
  await Promise.all([
    loadAvailableChannels(),
    loadChannelStatus()
  ])
})
</script>

<style scoped>
.page-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.main-content {
  margin-top: 0;
}

.help-content h4 {
  margin: 16px 0 8px 0;
  color: #333;
  font-size: 14px;
}

.help-content ul {
  margin: 0 0 16px 0;
  padding-left: 18px;
}

.help-content li {
  margin-bottom: 4px;
  font-size: 13px;
  color: #666;
  line-height: 1.5;
}

:deep(.el-form-item__label) {
  font-weight: 500;
  color: #333;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

:deep(.el-divider__text) {
  font-weight: 500;
  color: #333;
}
</style>
